// import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Button,
  message,
  DatePicker,
  Radio,
  Input,
  Select,
} from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { viproomsaledetailTable, downloadviproomsaledetailExcel, queryCityInfo } from './service';
import moment from 'moment';
import styles from './index.less';
import { chargeTypeMap, payTypeMap } from '@/utils/constVal'
import { RedditSquareFilled } from '@ant-design/icons';

const { Option } = Select;

const TableList = (props) => {
  const { data: selectData } = useRequest(queryCityInfo);
  const [createModalVisible, handleModalVisible] = useState(false);
  const [exportFlag, handleExportFlag] = useState('')
  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();
  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(300);

  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])
  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }

  const columns = [
    {
      title: '销售日期',
      dataIndex: 'orderDate',
      width: 90,
      hideInSearch: true
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 90,
      hideInSearch: true
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 80,
      order: 19,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input
          {...rest}
          onChange={e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '订单起始日期',
      hideInTable: true,
      dataIndex: 'orderBeginDate',
      order: 18,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '订单结束日期',
      hideInTable: true,
      order: 17,
      dataIndex: 'orderEndDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      order: 16,
      dataIndex: 'beginDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order: 15,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '支付开始时间',
      hideInTable: true,
      dataIndex: 'payBeginDate',
      order: 14,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '支付结束时间',
      hideInTable: true,
      dataIndex: 'payEndDate',
      order: 13,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      order: 12,
      width: 80,
    },
    {
      title: '银行订单号',
      dataIndex: 'bankOrderNo',
      order: 11,
      width: 100,
    },
    {
      // 多个查询选项
      title: '出发地',
      dataIndex: 'org',
      width: 100,
      order: 10,
      hideInTable: true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '目的地',
      dataIndex: 'dst',
      width: 100,
      order: 9,
      hideInTable: true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '客票号',
      dataIndex: 'tktNo',
      order: 8,
      width: 80,
    },
    {
      title: '航线性质',
      key: 'segmentType',
      dataIndex: 'segmentType',
      order: 7,
      width: 120,
      filters: [
        { text: '国内', value: '国内' },
        { text: '国际', value: '国际' }
      ],
      valueEnum: {
        '': '全部',
        '国内': '国内',
        '国际': '国际'
      },
    },
    {
      title: '收款方式',//支付方式
      key: 'chargeType',
      initialValue: '',
      order: 6,
      dataIndex: 'chargeType',
      width: 100,
      filters: [
        { text: '微信', value: '微信' },
        { text: '银联', value: '银联' },
        { text: '支付宝', value: '支付宝' },
        { text: '现金', value: '现金' },
        { text: 'pos机', value: 'pos机' }
      ],
      valueEnum: {
        '': '全部',
        '0': '微信',
        '1': '银联',
        '2': '支付宝',
        '3': '现金',
        '4': 'pos机'
      },
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select
            style={{ width: '100%' }}
            mode="multiple"
            
            placeholder="请选择" {...rest}
            onChange={(v) => {
              ref.current.setFieldsValue({ chargeType: v });
            }}
          >
            {
              Object.keys(chargeTypeMap).map(item => (
                <Option value={item}>{chargeTypeMap[item]}</Option>
              ))
            }
          </Select>
        );
      },
    },
    {
      title: '支付状态',
      key: 'payType',
      initialValue: '',
      order: 5,
      hideInTable: true,
      dataIndex: 'payType',
      width: 100,
      filters: [
        // {text: '未支付', value: '未支付'},
        { text: '支付完成', value: '支付完成' },
        // {text: '支付失败', value: '支付失败'},
        { text: '退款成功', value: '退款成功' },
        { text: '退款失败', value: '退款失败' },
      ],
      valueEnum: {
        '': '全部',
        // '0':'未支付',
        '1': '支付完成',
        // '2': '支付失败',
        '3': '退款成功',
        '4': '退款失败',
      },
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select
            style={{ width: '100%' }}
            mode="multiple"
            
            placeholder="请选择" {...rest}
            onChange={(v) => {
              ref.current.setFieldsValue({ payType: v });
            }}
          >
            {
              Object.keys(payTypeMap).map(item => (
                <Option value={item}>{payTypeMap[item]}</Option>
              ))
            }
          </Select>
        );
      },
    },
    {
      title: '订单状态',
      key: 'orderStatus',
      initialValue: '',
      dataIndex: 'orderStatus',
      order: 4,
      width: 100,
      filters: [
        // {text: '未支付', value: '0'},
        { text: '支付失败', value: '支付失败' },
        // {text: '支付取消',value: '2'},
        { text: '支付完成', value: '支付完成' },
        // {text: '退款中', value: '4'},
        { text: '退款失败', value: '退款失败' },
        { text: '退款成功', value: '退款成功' },
        { text: '取消', value: '取消' },
      ],
      valueEnum: {
        '': '全部',
        // '0': '未支付',
        '1': '支付失败',
        // '2': '支付取消',
        '2': '支付完成',
        // '4': '退款中',
        '4': '退款失败',
        '5': '退款成功',
        '6': '取消',
      },
    },
    {
      // 多个查询选项
      title: '销售渠道',//后台返回
      key: 'sellChannel',
      dataIndex: 'sellChannel',
      order: 3,
      width: 100,
      initialValue: '', //缺个默认接口服务航站
      // renderFormItem: (_, { ...rest }, form) => {
      //   return (
      //     <Select
      //       allowClear={true}
      //       showSearch
      //       placeholder="请选择"
      //       defaultActiveFirstOption={false}
      //       showArrow={false}
      //       filterOption={true}
      //       optionFilterProp="children"
      //       notFoundContent={null}
      //       {...rest}
      //     >
      //       {selectData &&
      //         selectData.map((v, i) => {
      //           return (
      //             <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
      //           )
      //         })
      //       }
      //     </Select>
      //   );
      // },
    },
    {
      title: '缴纳流水号',
      dataIndex: 'payNumber',
      order: 2,
      width: 100,
    },
    {
      title: '航段',
      hideInSearch: true,
      dataIndex: 'flightRoute',
      width: 60,
    },
    {
      title: '人数',
      hideInSearch: true,
      dataIndex: 'customerNo',
      width: 60,
    },
    {
      title: '付费进厅金额',
      hideInSearch: true,
      dataIndex: 'price',
      width: 100,
    },
    {
      title: '支付状态',
      hideInSearch: true,
      dataIndex: 'applyStatus',
      width: 80,
    },
    {
      title: '支付时间',
      hideInSearch: true,
      dataIndex: 'operationDate',
      width: 100,
    },
    {
      title: '现金缴纳单号',
      hideInSearch: true,
      dataIndex: 'cashNo',
      width: 120,
    },
    {
      title: '备注',
      hideInSearch: true,
      dataIndex: 'remark',
      width: 60,
    },
    {
      title: '操作人',
      hideInSearch: true,
      dataIndex: 'userName',
      width: 80,
    },
    {
      title: '操作人号',
      hideInSearch: true,
      dataIndex: 'userNo',
      width: 90,
    },
    {
      title: '部门',
      hideInSearch: true,
      dataIndex: 'department',
      width: 80,
    },
    {
      title: '行政区域',
      dataIndex: 'areaCompany',
      order: 1,
      width: 80,
    }
  ];
  const [inited, setInited] = useState(false);
  const [firstLoadDate, setFirstLoadDate] = useState(true);
  useEffect(() => {
    if (actionRef.current && inited) {
      reloadTable();
    } else {
      setInited(true);
    }
  }, [inited]);

  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {
    params['orderBeginDate'] = params.orderBeginDate ? params.orderBeginDate.format('YYYY-MM-DD') : '';
    params['orderEndDate'] = params.orderEndDate ? params.orderEndDate.format('YYYY-MM-DD') : '';
    if (!isCollapse) {
      return { ...params }
    } else {
      if (event && event.target && event.target.querySelector && event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('orderBeginDate') === -1) {
          params.orderBeginDate = ''
        }
        if (Object.keys(params).indexOf('orderEndDate') === -1) {
          params.orderEndDate = ''
        }
      } else if (event && event.target && event.target.querySelector && event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          orderBeginDate: moment(),
          orderEndDate: moment(),
        })
      }
      return { ...params }
    }
  }, []);
  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const [searchParams, handleSearchParams] = useState() // 存储搜索条件
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys);
    handleSelectedRows(selectedRows);
  };
  // 设置选中的值
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };
  //导出方法
  const handleExport = () => {
    if (!exportFlag) {
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = downloadviproomsaledetailExcel(searchParams)
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time = moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
        elink.download = '贵宾室销售报表' + time + '.xls'
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <>
      <ProTable
        options={{ density: false, fullScreen: true, reload: false, setting: true }}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        scroll={{ x: 1100, y: height }}
        size='small'
        className={`${styles.viproomsaleCharts} rest-pro-table-form-compact ${isCollapse ? '' : 'collapse'}`}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val);
          },
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
        toolBarRender={() => [
          <AuthComponent authCode="mkt.viproomsalecharts.export">
            <Button icon="download" type="primary" onClick={handleExport} selectedKeys={[]} style={{ padding: '0px 0px 0px 8px', width: '73px' }}>
              导出
          </Button>
          </AuthComponent>
        ]}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>贵宾室销售表</span>
          </div>
        }
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['orderBeginDate'] && !params['orderEndDate'] && firstLoadDate) {
            setFirstLoadDate(false)
            params['orderBeginDate'] = moment().format('YYYY-MM-DD');
            params['orderEndDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              orderBeginDate: moment(),
              orderEndDate: moment()
            })
          }
          if (!params.beginDate) {
            ref.current.setFieldsValue({
              beginDate: ''
            })
          } else {
            params['beginDate'] = params.beginDate ? params.beginDate.format('YYYY-MM-DD') : '';
          }
          if (!params.endDate) {
            ref.current.setFieldsValue({
              endDate: ''
            })
          } else {
            params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';
          }
          if (!params.payBeginDate) {
            ref.current.setFieldsValue({
              payBeginDate: ''
            })
          } else {
            params['payBeginDate'] = params.payBeginDate ? params.payBeginDate.format('YYYY-MM-DD') : '';
          }
          if (!params.payEndDate) {
            ref.current.setFieldsValue({
              payEndDate: ''
            })
          } else {
            params['payEndDate'] = params.payEndDate ? params.payEndDate.format('YYYY-MM-DD') : '';
          }
          // if (!params['org']) {
          //   ref.current.setFieldsValue({
          //     org: ''
          //   })
          // }
          if (!params['flightNo']) {
            ref.current.setFieldsValue({
              flightNo: ''
            })
          }
          // if (!params['dst']) {
          //   ref.current.setFieldsValue({
          //     dst: ''
          //   })
          // }
          if (!params['chargeType']) {
            ref.current.setFieldsValue({
              chargeType: Object.keys(chargeTypeMap)
            })
          }
          if (!params['sellChannel']) {
            ref.current.setFieldsValue({
              sellChannel: ''
            })
          }
          if (!params['segmentType']) {
            ref.current.setFieldsValue({
              segmentType: ''
            })
          }
          if (!params['orderNo']) {
            ref.current.setFieldsValue({
              orderNo: ''
            })
          }
          if (!params['bankOrderNo']) {
            ref.current.setFieldsValue({
              bankOrderNo: ''
            })
          }
          if (!params['tktNo']) {
            ref.current.setFieldsValue({
              tktNo: ''
            })
          }
          if (!params['orderStatus']) {
            ref.current.setFieldsValue({
              orderStatus: ''
            })
          }
          if (!params['payNumber']) {
            ref.current.setFieldsValue({
              payNumber: ''
            })
          }
          if (!params['payType']) {
            ref.current.setFieldsValue({
              payType: Object.keys(payTypeMap)
            })
          }
          if (!params['areaCompany']) {
            ref.current.setFieldsValue({
              areaCompany: ''
            })
          }
          params.chargeType = params.chargeType.toString();
          params.payType = params.payType.toString();
          handleSearchParams(params);
          return viproomsaledetailTable(params);
        }}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        onRow={record => {
          return {
            onClick: () => {
            },
          };
        }}
        columns={columns}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
      />
    </>
  );
};

export default Form.create()(TableList);
